package com.chandra.pos.employee.web;

import com.chandra.pos.SearchCriteria;
import com.chandra.pos.employee.dao.entity.Employee;
import com.chandra.pos.employee.exception.SystemUserNotFoundException;
import com.chandra.pos.employee.model.UserStatusType;
import com.chandra.pos.employee.service.IEmployeeManager;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * Customer Managed Bean
 *
 * @author onlinetechvision.com
 * @version 1.0.0
 * @since 25 Mar 2012
 */
@Named("systemUserMB")
public class EmployeeManagedBean extends LazyDataModel<Employee> implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";




    //Spring Customer Service is injected...
    @Inject
    IEmployeeManager systemUserService;

     private Long id;

    private String surname;

    private String firstName;

    private String lastName;

    private String nickName;

    private String email;

    private String primaryContact;

    private String secondaryContact;

    private String city;
    private String country;

    private String password;

    private String address;

    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    private Employee selectedCustomer;



    public EmployeeManagedBean() {

    }

    public Employee getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(Employee selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    /**
     * Add Customer
     *
     * @return String - Response Message
     */
    public void  addUser(ActionEvent actionEvent) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        boolean loggedIn = false;
        try {
            systemUserService.getUserDetail(getUserName());
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "Account already exist.");
        } catch (SystemUserNotFoundException e) {
            try {
                Employee customer = new Employee();
                // customer.setId(getId());
                Random random=new Random();
                customer.setId(random.nextLong());

                customer.setAddress(getAddress());
                customer.setFirstName(getFirstName());
                customer.setLastName(getLastName());
                customer.setCity(getCity());
                customer.setUserName(getUserName());
                customer.setPassword(getPassword());
                customer.setAccountStatus(UserStatusType.ACTIVE);
                customer.setPrimaryContact(getPrimaryContact());
                customer.setSecondaryContact(getSecondaryContact());
                customer.setEmail(getEmail());
                //customer.setUserName(getUserName());
                systemUserService.addUser(customer);

                reset();
                loggedIn = true;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Account created.", "Account created succesfully.");

            } catch (DataAccessException e1) {
                loggedIn = false;
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", e1.getMessage());

            }
        }


        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("loggedIn", loggedIn);


    }
    public LazyDataModel<Employee> getLazyModel() {
        return this;
    }

    /**
     * Reset Fields
     */
    public void reset() {
        this.setId(0l);
        this.setFirstName("");
        this.setLastName("");
        this.setCity("");
        this.setEmail("");
        this.setAddress("");
        this.setNickName("");
        this.setCountry("");
        this.setSurname(null);
        this.setPrimaryContact("");
        this.setSecondaryContact("");
        this.setUserName("");
    }

    public void onRowSelect(SelectEvent event){
        FacesMessage msg = new FacesMessage("Customer Selected", ((Employee) event.getObject()).getName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }







    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPrimaryContact() {
        return primaryContact;
    }

    public void setPrimaryContact(String primaryContact) {
        this.primaryContact = primaryContact;
    }

    public String getSecondaryContact() {
        return secondaryContact;
    }

    public void setSecondaryContact(String secondaryContact) {
        this.secondaryContact = secondaryContact;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }



    /**
     * Get Customer Id
     *
     * @return int - Customer Id
     */
    public Long getId() {
        return id;
    }

    /**
     * Set Customer Id
     *
     * @param id - Customer Id
     */
    public void setId(Long id) {
        this.id = id;
    }



    /**
     * Get Customer Surname
     *
     * @return String - Customer Surname
     */
    public String getSurname() {
        return surname;
    }

    /**
     * Set Customer Surname
     *
     * @param surname - Customer Surname
     */
    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public Employee getRowData(String rowKey) {
        Employee customer = systemUserService.getUserById(Long.valueOf(rowKey));

        return customer;

    }

    @Override
    public Long getRowKey(Employee car) {
        return car.getId();
    }

    @Override
    public List<Employee> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        SearchCriteria searchCriteria=new SearchCriteria();

           searchCriteria.setPageSize(pageSize);
        searchCriteria.setFirst(first);
        searchCriteria.setSortField(sortField);
        searchCriteria.setSortOrder(sortOrder);
        searchCriteria.setFilters(filters);

       // PageRequest pageRequest=new PageRequest(first,pageSize, new Sort(Sort.Direction.ASC, sortField)) ;
        PageRequest pageRequest=new PageRequest(first,pageSize) ;


        List<Employee> data = systemUserService.searchUsers(searchCriteria);


        int dataSize = data.size();
        this.setRowCount(dataSize);

       return data;
    }


    public List<Employee> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String,String> filters) {

        // PageRequest pageRequest=new PageRequest(first,pageSize, new Sort(Sort.Direction.ASC, sortField)) ;
        PageRequest pageRequest=new PageRequest(first,pageSize) ;


        Page data = systemUserService.getUsers(pageRequest);


        int dataSize = data.getSize();
        this.setRowCount(dataSize);

        return data.getContent();
    }


}